package com.zyx.maildemo.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @ClassName: EmailUtils
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2019/7/27 12:19
 */
@Slf4j
@Component
public class EmailUtils {

    @Value("${spring.mail.username}")
    private String form;

    @Autowired
    private JavaMailSender sender;

    /**
     * 发送注册确定邮件
     * @param to 接收方
     * @param title 邮件标题
     * @param html 邮件内容
     */
    @Async
    public void send(String to, String title, String html) {
        MimeMessage mimeMessage = sender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(form);
            helper.setTo(to);
            helper.setSubject(title);
            helper.setText(html, true);
            sender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("error {}", e);
            log.error("邮件发送失败 {}", e.getMessage());
        }
    }

}
